package produceAndConsum;

public class Producer implements Runnable{
    synchronized void waitEmpty(Semaphore s) throws InterruptedException {
        s.empty--;
        if(s.empty<0){
            s.processlist.addLast(Thread.currentThread());
            Thread.currentThread().sleep(1000*60);
        }
    }

    synchronized void waitMutex(Semaphore s) throws InterruptedException {
        s.mutex--;
       if(s.mutex<0){
           s.mutexlist.addLast(Thread.currentThread());
           Thread.currentThread().sleep(1000*60);

       }
    }

    synchronized void signalMutex(Semaphore s){
        s.mutex++;
        if(s.mutex<=0){
            s.mutexlist.getFirst().interrupt();
            s.mutexlist.removeFirst();
        }
    }

    synchronized void signalFull(Semaphore s){
       s.full++;
       if(s.full<=0){
           s.processlist.getFirst().interrupt();
           s.processlist.removeFirst();
       }
    }

     void produce() throws InterruptedException {
        while (true) {
            try {
                waitEmpty(Main.s);
            } catch (InterruptedException e) {
                //e.printStackTrace();
            }
            try {
                waitMutex(Main.s);
            } catch (InterruptedException e) {
                //e.printStackTrace();
            }
            Thread.sleep(2000);
            Main.buffer[Main.nextin] = '1';
            Main.nextin = (Main.nextin + 1) % Main.s.K;
            Main.s.count++;
            Main.s.value--;
            System.out.println(Thread.currentThread().getName() + "生产了,此时满缓冲区为:" + Main.s.count + " 空缓冲区为:" + Main.s.value);
            signalMutex(Main.s);
            signalFull(Main.s);
        }
    }

    @Override
    public void run() {
        try {
            produce();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
